import { Plugin } from 'vite';
import fs from 'fs';
import path from 'path';
import dayjs from 'dayjs';

export default function updateTimePlugin(options: { filePath: string }): Plugin {
  return {
    name: 'update-time-plugin',
    buildStart() {
      const currentTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
      const filePath = path.resolve(process.cwd(), options.filePath);

      // 确保文件存在，如果不存在则创建它
      if (!fs.existsSync(filePath)) {
        fs.writeFileSync(filePath, `export const buildTime = "${currentTime}";`);
      } else {
        // 读取文件内容，并替换打包时间
        const fileContent = fs.readFileSync(filePath, 'utf8');
        const updatedContent = fileContent.replace(/export const buildTime = "[^"]*";/, `export const buildTime = "${currentTime}";`);
        fs.writeFileSync(filePath, updatedContent);
      }
    }
  };
}